import requests
import asyncio
import aiohttp
import aiofiles
import re


url = "https://www.fjwhpm.com/play/147468-2-1/"


def get_m3u8_url(url):
    print('get_m3u8_url')
    rsp = requests.get(url)
    m3u8_url = re.findall('"url":"(.*?)","url_next"', rsp.content.decode())[0]
    # https:\/\/s2.bfzycdn.com\/video\/jingtianbangjiatuan\/HD\u4e2d\u5b57\/index.m3u8
    # m3u8_url = "https:\/\/s2.bfzycdn.com\/video\/jingtianbangjiatuan\/HD\\u4e2d\\u5b57\/index.m3u8"
    m3u8_url = m3u8_url.replace('\/', '/')  # https://s2.bfzycdn.com/video/jingtianbangjiatuan/HD\u4e2d\u5b57/index.m3u8
    m3u8_url = m3u8_url.encode('utf-8').decode('unicode_escape')  # https://s2.bfzycdn.com/video/jingtianbangjiatuan/HD中字/index.m3u8
    return m3u8_url


async def download_ts(url, name):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as rsp:
            async with aiofiles.open(f'bfzyplayer_rsc/{name}', 'wb') as f:
                await f.write(await rsp.content.read())
                print(f'{name}下载完毕')


async def main():
    m3u8_url = get_m3u8_url(url)
    with requests.get(m3u8_url) as rsp:
        with open('bfzyplayer_m3u8.txt', 'wb') as f:
            f.write(rsp.content)
    domain = "https://s2.bfzycdn.com/video/jingtianbangjiatuan/HD%E4%B8%AD%E5%AD%97/"
    tasks = []
    with open('bfzyplayer_m3u8.txt', 'r') as f:
        for line in f:
            if line.startswith('#') or line.startswith('/'):
                continue
            line = line.strip()
            ts_url = domain + line
            tasks.append(asyncio.create_task(download_ts(ts_url, line)))
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())
